<form class="layui-form seller-form" action="">
    <div class="layui-form-item">
        <div style="position:relative;display:inline-block; margin-right: 5px">
            <button type="button" class="layui-btn layui-btn-sm"
                style="margin-bottom: 10px; background-color: #1E9FFF !important;" id="importFile">选择文件</button>
        </div>
        <div class="layui-inline">
            <button type="button" class="layui-btn layui-btn-sm" lay-submit lay-filter="downloadTemplate">模版下载(不支持迅雷等下载工具)</button>
        </div>
        <div class="layui-inline">
            <button type="button" id="btnBookplanReload" class="layui-btn layui-btn-sm layui-btn-disabled" lay-submit 
                lay-filter="reload" disabled="disabled">重新加载</button>
        </div>
        <div class="layui-inline" style="float:right">
            <button type="button" id="btnBookplanImport" class="layui-btn layui-btn-sm layui-btn-disabled" lay-submit
                lay-filter="import" disabled="disabled">数据导入</button>
        </div>
    </div>
</form>

<div id="exportBookPlanErrData" style="display: none;">
    <form class="layui-form export-form" action="">
        <div class="layui-form-item">
            <div class="layui-margin-10">
                <blockquote class="layui-elem-quote layui-text">
                    请先筛选要导出的用户，默认导出全部
                </blockquote>
            </div>

            <div class="layui-inline">
                <label class="layui-form-label">任务名称：</label>
                <input type="text" name="taskname" lay-verify="title" style="width:200px;" placeholder="请输入任务名称"
                    autocomplete="off" class="layui-input">
            </div>
        </div>
    </form>
</div>

<div class="table-body">
    <table id="demo" lay-filter="test"></table>
</div>

<script src="../layui/layui.js"></script>

<script>
    var table;
    var filePath;
    layui.use(['upload', 'form', 'laydate', 'table'], function () {
        var form = layui.form;
        var upload = layui.upload;
        var uploadInstance;
        var uploadInst;     // 用于重新加载
        var uploadIndex;    // 用于重新加载
        var uploadFile;     // 用于重新加载
        var allData;        // 全部数据
        var errData;        // 错误数据
        var count;          // 全部数据总数
        var errCount;       // 错误数据总数
        var fileId;         // 文件索引
        var filePath;       // 文件路径
        form.render();

        uploadInstance = upload.render({
            elem: '#importFile'
            , url: "{:url('Files/uploadXls?type=bookplan')}"
            , auto: false
            , exts: 'xls'
            , accept: 'file'
            , before: function (obj) {
                $('#btnBookplanImport').addClass("layui-btn-disabled");
                $('#btnBookplanImport').attr("disabled", true);
                
                $('#btnBookplanReload').addClass("layui-btn-disabled");
                $('#btnBookplanReload').attr("disabled", true);
            }
            , choose: function (obj) {
                layer.load(1);
                // 判断文件格式
                obj.preview(function (index, file, result) {
                    // 这里需要通过后缀名判断，file['type']有许多电脑并不支持
                    if(file['name'].substr(file['name'].length-4)!='.xls') {
                    //if (file['type'] != 'application/vnd.ms-excel') {
                        layer.open({
                            type: 1
                            , offset: 'auto'
                            , id: 'warnDlg'
                            , content: '<div style="padding: 20px">文件格式错误，请选择xls格式的文件！</div>'
                            , btn: '关闭'
                            , btnAlign: 'c' //按钮居中
                            , shade: 0.3 //不显示遮罩
                            , yes: function () {
                                layer.closeAll();
                                return;
                            }
                        });
                    } else {
                        filePath = file.filePath;
                        //文件上传并判断文件内容是否与模版匹配、数据有效性校验
                        obj.upload(index, file);
                        uploadInst = obj;
                        uploadIndex = index;
                        uploadFile = file;
                    }
                });
            }
            , done: function (res, index, upload) {
                if(res['code'] == -1 || 
                res['status'] == false) {
                    layer.open({
                        type: 1
                        , offset: 'auto'
                        , id: 'warnDlg'
                        , content: '<div style="padding: 20px">' + res['msg'] + '</div>'
                        , btn: '关闭'
                        , btnAlign: 'c' //按钮居中
                        , shade: 0.3 //不显示遮罩
                        , success: function (layero, index) {
                            this.enterEsc = function (event) {
                                if (event.keyCode === 13 ||
                                event.keyCode === 8) {
                                    layer.close(index);
                                    return false; //阻止系统默认回车事件
                                }
                            };
                            $(document).on('keydown', this.enterEsc);	//监听键盘事件，关闭层
                        }
                        , end: function () {
                            $(document).off('keydown', this.enterEsc);	//解除键盘关闭事件
                        }
                        , yes: function () {
                            layer.closeAll();
                            return;
                        }
                    });
                } else {
 
                    layer.closeAll('loading');
                    allData = JSON.parse(res['data']);
                    errData = JSON.parse(res['errData']);
                    count = JSON.parse(res['count']);
                    errCount = JSON.parse(res['errCount']);
                    fileId = res['fileId'];
                    filePath = res['filePath'];
                    var shouMsg = '';

                    $('#btnBookplanReload').removeClass("layui-btn-disabled");
                    $('#btnBookplanReload').removeAttr("disabled");
                    if (errCount == 0) {
                        shouMsg = '共' + count + '条数据，所有数据格式验证正确！';
                        $('#btnBookplanImport').removeClass("layui-btn-disabled")
                        $('#btnBookplanImport').removeAttr('disabled');
    
                        table = layui.table.render({
                            elem: '#demo',
                            height: 'full-115',
                            cellMinWidth: '80',
                            data: allData,
                            page: 'true',
                            limit: '20',
                            id: 'bookplanTable',
                            cols: [[
                                { type: 'numbers' },
                                { field: 'plan_year', title: '年度', width: 100 },
                                { field: 'plan_season', title: '季度', width: 100 },
                                { field: 'grade', title: '年级', width: 100 },
                                { field: 'degree', title: '层次', width: 100 },
                                { field: 'bmmc', title: '院系', width: 150 },
                                { field: 'zymc', title: '专业名称', width: 150 },
                                { field: 'dir', title: '方向', width: 100 },
                                { field: 'course_name', title: '课程名称', width: 150 },
                                { field: 'book_name', title: '教材名称', width: 150 },
                                { field: 'book_author', title: '主编', width: 150 },
                                { field: 'book_concern', title: '出版社', width: 150 },
                                { field: 'book_isbn', title: 'ISBN书号', width: 100 },
                                { field: 'book_edition', title: '版次', width: 100 },
                                { field: 'book_date', title: '出版年限', width: 100 },
                                { field: 'plan_student', title: '学生数量', width: 100 },
                                { field: 'plan_book_num', title: '教材数量', width: 100 },
                                { field: 'book_reward', title: '获奖情况', width: 150 },
                                { field: 'desc', title: '备注', width: 300 }
                            ]]
                        });
                    } else {
                        shouMsg = '共' + count + '条数据，错误数据共' + errCount + '条，请按提示先修改好数据后再导入！';
                        table = layui.table.render({
                            elem: '#demo',
                            height: 'full-115',
                            cellMinWidth: '80',
                            data: allData,
                            page: 'true',
                            limit: '20',
                            toolbar: '#toolbarDemo',
                            defaultToolbar: [],
                            id: 'bookplanTable',
                            cols: [[
                                { type: 'numbers' },
                                { field: 'plan_year', title: '年度', width: 100 },
                                { field: 'plan_season', title: '季度', width: 100 },
                                { field: 'grade', title: '年级', width: 100 },
                                { field: 'degree', title: '层次', width: 100 },
                                { field: 'bmmc', title: '院系', width: 150 },
                                { field: 'zymc', title: '专业名称', width: 150 },
                                { field: 'dir', title: '方向', width: 100 },
                                { field: 'course_name', title: '课程名称', width: 150 },
                                { field: 'book_name', title: '教材名称', width: 150 },
                                { field: 'book_author', title: '主编', width: 150 },
                                { field: 'book_concern', title: '出版社', width: 150 },
                                { field: 'book_isbn', title: 'ISBN书号', width: 100 },
                                { field: 'book_edition', title: '版次', width: 100 },
                                { field: 'book_date', title: '出版年限', width: 100 },
                                { field: 'plan_student', title: '学生数量', width: 100 },
                                { field: 'plan_book_num', title: '教材数量', width: 100 },
                                { field: 'book_reward', title: '获奖情况', width: 150 },
                                { field: 'desc', title: '备注', width: 300 }
                            ]]
                        });
                    }

                    layer.open({
                        type: 1
                        , offset: 'auto'
                        , id: 'warnDlg'
                        , content: '<div style="padding: 20px">' + shouMsg + '</div>'
                        , btn: '关闭'
                        , btnAlign: 'c' //按钮居中
                        , shade: 0.3 //不显示遮罩
                        , success: function (layero, index) {
                            this.enterEsc = function (event) {
                                if (event.keyCode === 13 ||
                                event.keyCode === 8) {
                                    layer.close(index);
                                    return false; //阻止系统默认回车事件
                                }
                            };
                            $(document).on('keydown', this.enterEsc);	//监听键盘事件，关闭层
                        }
                        , end: function () {
                            $(document).off('keydown', this.enterEsc);	//解除键盘关闭事件
                        }
                        , yes: function () {
                            layer.closeAll();
                            return;
                        }
                    });
                }
            }
            ,error: function(){
                layer.open({
                    type: 1
                    , offset: 'auto'
                    , id: 'warnDlg'
                    , content: '<div style="padding: 20px">上传文件出错，请重新选择文件！</div>'
                    , btn: '关闭'
                    , btnAlign: 'c' //按钮居中
                    , shade: 0.3 //不显示遮罩
                    , yes: function () {
                        layer.closeAll();
                        return;
                    }
                });
                layer.closeAll('loading');
                $('#btnBookplanReload').removeClass("layui-btn-disabled");
                $('#btnBookplanReload').removeAttr("disabled");
            }
        });

        //头工具栏事件
        layui.table.on('toolbar(test)', function (obj) {
            switch (obj.event) {
                case 'showType':
                    var data;
                    var title = document.getElementById("showType").innerHTML;
                    if (title == "错误数据") {
                        data = errData;
                    } else {
                        data = allData;
                    }

                    table = layui.table.render({
                        elem: '#demo',
                        height: 'full-115',
                        cellMinWidth: '80',
                        data: data,
                        page: 'true',
                        limit: '20',
                        toolbar: '#toolbarDemo',
                        defaultToolbar: [],
                        id: 'bookplanTable',
                        cols: [[
                            { type: 'numbers' },
                            { field: 'plan_year', title: '年度', width: 100 },
                            { field: 'plan_season', title: '季度', width: 100 },
                            { field: 'grade', title: '年级', width: 100 },
                            { field: 'degree', title: '层次', width: 100 },
                            { field: 'bmmc', title: '院系', width: 150 },
                            { field: 'zymc', title: '专业名称', width: 150 },
                            { field: 'dir', title: '方向', width: 100 },
                            { field: 'course_name', title: '课程名称', width: 150 },
                            { field: 'book_name', title: '教材名称', width: 150 },
                            { field: 'book_author', title: '主编', width: 150 },
                            { field: 'book_concern', title: '出版社', width: 150 },
                            { field: 'book_isbn', title: 'ISBN书号', width: 100 },
                            { field: 'book_edition', title: '版次', width: 100 },
                            { field: 'book_date', title: '出版年限', width: 100 },
                            { field: 'plan_student', title: '学生数量', width: 100 },
                            { field: 'plan_book_num', title: '教材数量', width: 100 },
                            { field: 'book_reward', title: '获奖情况', width: 150 },
                            { field: 'desc', title: '备注', width: 300 }
                        ]]

                    });
 
                    if (title == "错误数据") {
                        document.getElementById("showType").innerHTML = "全部数据";
                    } else {
                        document.getElementById("showType").innerHTML = "错误数据";
                    }
                    break;
                case 'exportErrData':
                    layer.open({
                    type: 1,
                    title: '错误数据导出',
                    area: ['400px', '248px'], //宽高
                    btn: ['确定', '取消'],
                    content: $("#exportBookPlanErrData").html(),
                    success: function () {
                        $(':focus').blur();
                        this.enterEsc = function(event){
                            if(event.keyCode === 13){
                                if(!$(".layui-layer-btn0").hasClass("layui-btn-disabled")){
                                    $(".layui-layer-btn0").addClass("layui-btn-disabled");

                                    //判断是否有选中
                                    var filter = "fileId=" +fileId+ "&filePath=" + filePath;
                                    $(".export-form:last").append("<input type='hidden' name='filter' value='" + filter + "'>");
                                    var data = $(".export-form:last").serializeArray();
                                    data.push({ 'name': 'model', 'value': 'BookPlanErrData' });

                                    if($.trim(data[0]['value']) == '') {
                                        layer.msg('请填写任务名称！', { time: 1300 });
                                        $(".layui-layer-btn0").removeClass("layui-btn-disabled");
                                        return false;
                                    }

                                    JsPost("{:url('Ietask/export')}", data, function (res) {
                                            layer.msg(res.msg, { time: 1500 }, function () {
                                                if (res.status) {
                                                    layer.closeAll();
                                                    //执行跳转
                                                    var topLayui = parent === self ? layui : top.layui;
                                                    topLayui.index.openTabsPage('/manage/ietask/index.html', '导入导出');
                                                } else {
                                                    $(".layui-layer-btn0").removeClass("layui-btn-disabled");
                                                }
                                            });
                                        }
                                    );
                                }
                                return false; //阻止系统默认回车事件
                            }
                        };
                        $(document).on('keydown', this.enterEsc);	//监听键盘事件，关闭层
                    },
                    yes: function () {
                        if(!$(".layui-layer-btn0").hasClass("layui-btn-disabled")){
                            $(".layui-layer-btn0").addClass("layui-btn-disabled");

                            //判断是否有选中
                            var filter = "fileId=" +fileId+ "&filePath=" + filePath;
                            $(".export-form:last").append("<input type='hidden' name='filter' value='" + filter + "'>");
                            var data = $(".export-form:last").serializeArray();
                            data.push({ 'name': 'model', 'value': 'BookPlanErrData' }, { 'name': 'fileId', 'value': fileId }, { 'name': 'filePath', 'value': filePath });
                            
                            if($.trim(data[0]['value']) == '') {
                                layer.msg('请填写任务名称！', { time: 1300 });
                                $(".layui-layer-btn0").removeClass("layui-btn-disabled");
                                return false;
                            }
 
                            JsPost("{:url('Ietask/export')}", data, function (res) {
                                    layer.msg(res.msg, { time: 1500 }, function () {
                                        if (res.status) {
                                            layer.closeAll();
                                            //执行跳转
                                            var topLayui = parent === self ? layui : top.layui;
                                            topLayui.index.openTabsPage('/manage/ietask/index.html', '导入导出');
                                        } else {
                                            $(".layui-layer-btn0").removeClass("layui-btn-disabled");
                                        }
                                    });
                                }
                            );
                        }
                    }, btn2: function () {
                        layer.closeAll();
                    }, end: function(){
                        $(document).off('keydown', this.enterEsc);	        //解除键盘关闭事件
                    }
                });
                break;
            };
        });

        // 下载模版
        layui.form.on('submit(downloadTemplate)', function () {
            window.location.href = "{:url('ietask/importTemplete',['tplName'=>'bookplan'])}";
            return false;
        });

        // 重新加载
        layui.form.on('submit(reload)', function () {
            layer.load(1);
            uploadInst.upload(uploadIndex, uploadFile);
            return false;
        });

        // 导入
        layui.form.on('submit(import)', function () {
            layer.load(1);
            $.ajax({
                url: "{:url('ietask/import')}",
                type: 'post',
                data: { 'fileId': fileId, 'model': 'BookPlan' },
                dataType: 'json',
                success: function (e) {
                    layer.closeAll('loading');
                    $('#btnBookplanImport').addClass("layui-btn-disabled");
                    $('#btnBookplanImport').attr("disabled", true);
                     
                    $('#btnBookplanReload').addClass("layui-btn-disabled");
                    $('#btnBookplanReload').attr("disabled", true);

                    layer.open({
                        type: 1
                        , offset: 'auto'
                        , id: 'layerDemoAuto'
                        , content: '<div style="padding: 20px 100px;">' + e.msg + '</div>'
                        , btn: '关闭'
                        , btnAlign: 'c' //按钮居中
                        , shade: 0.3 //不显示遮罩
                        , success: function (layero, index) {
                            this.enterEsc = function (event) {
                                if (event.keyCode === 13 ||
                                event.keyCode === 8) {
                                    layer.close(index);
                                    return false; //阻止系统默认回车事件
                                }
                            };
                            $(document).on('keydown', this.enterEsc);	//监听键盘事件，关闭层
                        }
                        , end: function () {
                            $(document).off('keydown', this.enterEsc);	//解除键盘关闭事件
                        }
                        , yes: function () {
                            parent.layui.admin.events.changeTabAndRefresh('/manage/book_plan/index.html', 'bookPlanTable');
                        }, close: function () {
                            console.log('close');
                        }
                    });
                }
            })
            return false;
        });
    }); 
</script>

<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" id = "showType" lay-event="showType">错误数据</button>
        <button class="layui-btn layui-btn-sm" id = "exportErrData" lay-event="exportErrData">错误数据导出</button>
    </div>
</script>